
package c.x.jy.admin.oauth2;

import java.io.IOException;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSON;

import c.x.jy.admin.util.HttpContextUtils;
import c.x.jy.common.utils.CookieUtil;
import c.x.jy.common.utils.R;

/**
 * oauth2过滤器
 *
 * extends AuthenticatingFilter
 */
public class OAuth2Filter extends AuthenticatingFilter {

	@Override
	protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception {
		// 获取请求token
		String token = getRequestToken((HttpServletRequest) request);

		if (StringUtils.isBlank(token)) {
			return null;
		}
		return new OAuth2Token(token);
	}

	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
		if (((HttpServletRequest) request).getMethod().equals(RequestMethod.OPTIONS.name())) {
			return true;
		}

		return false;
	}

	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		// 获取请求token，如果token不存在，直接返回401
		String token = getRequestToken((HttpServletRequest) request);
	 
		if (StringUtils.isBlank(token)) {
			HttpServletResponse httpResponse = (HttpServletResponse) response;
			if (SecurityUtils.getSubject().isAuthenticated()) {
				SecurityUtils.getSubject().logout();
			}
			
			  httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
			   httpResponse.setHeader("Access-Control-Allow-Origin",  HttpContextUtils.getOrigin());
			  
		  String json = JSON.toJSONString(R.error(HttpStatus.SC_UNAUTHORIZED, "invalid token"));
			httpResponse.getWriter().print(json);
			 String contextPath = ((HttpServletRequest) request).getContextPath();
			//httpResponse.sendRedirect(contextPath+"/");
			System.out.println("invalid token:" + contextPath  +" token:"+token);
			return false;
		}

		if (!SecurityUtils.getSubject().isAuthenticated()) {
			try {
				SecurityUtils.getSubject().login(new OAuth2Token(token));
			} catch (Exception e) {
				e.printStackTrace();
				HttpServletResponse httpResponse = (HttpServletResponse) response;
				String contextPath = ((HttpServletRequest) request).getContextPath();
			//	httpResponse.sendRedirect(contextPath + "/");
				
				  httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
				   httpResponse.setHeader("Access-Control-Allow-Origin",  HttpContextUtils.getOrigin());
				  
			  String json = JSON.toJSONString(R.error(HttpStatus.SC_UNAUTHORIZED, "invalid token"));
		 
				httpResponse.getWriter().print(json);
	
				System.out.println("invalid token11:" + contextPath+" token:"+token);
			
				 return false;
			}

		}


		return executeLogin(request, response);
	}

	@Override
	protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request,
			ServletResponse response) throws Exception {
		
//		SysUserEntityDto u=(SysUserEntityDto) subject.getPrincipal();
//		  if (token instanceof OAuth2Token) {
//			  OAuth2Token t = (OAuth2Token) token;
//			  System.out.println("success:::"+t.getPrincipal());
//			  System.out.println("user:::"+ ""+JSON.toJSONString(u));
//			 RedisUtils.redisUtils.set(t.getPrincipal(),u , Long.valueOf(LoginController.EXPIRE));
//		} 
//		System.out.println("success");
	
		return true;
	}

	@Override
	protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request,
			ServletResponse response) {

		HttpServletResponse httpResponse = (HttpServletResponse) response;
		httpResponse.setContentType("application/json;charset=utf-8");
		httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
		httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtils.getOrigin());
		try {
			
			  String json = JSON.toJSONString(R.error(HttpStatus.SC_UNAUTHORIZED, "登陆失败"));
				 
				httpResponse.getWriter().print(json);
			//String contextPath = ((HttpServletRequest) request).getContextPath();
			//httpResponse.sendRedirect(contextPath + "/login.html");
		} catch (IOException e1) {
			e1.printStackTrace();
		}

		return false;
	}

	/**
	 * 获取请求的token
	 */
	private String getRequestToken(HttpServletRequest httpRequest) {
		String token = CookieUtil.getCookieValue(httpRequest, "token", true);
		if(token==null)token=httpRequest.getHeader("token");
		return token;
	}

}
